package com.hzw.saas.web.app.user.controller;

import com.hzw.saas.api.property.enmus.SysDictKeyEnum;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.verify.aspect.PuzzleVerify;
import com.hzw.saas.common.verify.enums.SmsType;
import com.hzw.saas.common.verify.service.IVerifyService;
import com.hzw.saas.web.app.aspect.RedisPeriodLock;
import com.hzw.saas.web.app.user.param.SmsVerifyParam;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Controller
@AllArgsConstructor
@Api(tags = "用户中心/短信验证")
public class SmsController {

    private final IVerifyService verifyService;

    @GetMapping("/user/verify/sms/{phone}")
    @SysLog(operation = "获取短信验证码", mode = 3)
    @PuzzleVerify(captchaVerification = "#token", pointJson = "#pointJson")
    @RedisPeriodLock(lockName = "verifySms", key = "#phone", expireKeyEnum = SysDictKeyEnum.VERIFY_LOCK_TIME, lockMsg = "请勿频繁获取验证码")
    @ApiOperation(value = "获取短信验证码", notes = "给指定的手机号发送验证短信")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String")
    @ApiResponses({@ApiResponse(code = 200, message = "发送短信验证码成功"), @ApiResponse(code = 400, message = "发送短信验证码失败")})
    @ApiOperationSort(1)
    public ResponseEntity<String> sendSms(@ApiParam(value = "手机号", required = true) @PathVariable String phone,
                                          @ApiParam(value = "verifyToken，二次校验参数(token)", required = true) @RequestParam(required = false) String token,
                                          @ApiParam(value = "pointJson，{\"x\":0,\"y\":0}", required = true) @RequestParam(required = false) String pointJson,
                                          @ApiParam(value = "类型,0重置密码|1注册用户|2支付|3更换手机号|4删除账户", required = true) @RequestParam Integer type) {
        SmsType smsType = SmsType.instance(type);
        if (smsType == null) {
            return ResponseEntity.badRequest().body("发送短信验证码失败, 请设置正确的Type");
        }

        if (verifyService.sendSmsVerifyCode(phone, smsType)) {
            return ResponseEntity.ok("发送短信验证码成功");
        }

        return ResponseEntity.badRequest().body("发送短信验证码失败");
    }

    @PutMapping("/user/verify/sms")
    @SysLog(operation = "验证短信验证码", mode = 3)
    @ApiOperation(value = "验证短信验证码", notes = "校验用户输入的短信验证码")
    @ApiResponses({@ApiResponse(code = 200, message = "验证成功"), @ApiResponse(code = 400, message = "验证失败")})
    @ApiOperationSort(2)
    public ResponseEntity<String> verifySms(@Validated @RequestBody SmsVerifyParam smsVerify) {
        boolean verify = verifyService.verify(smsVerify.getPhoneNo(), smsVerify.getVerifyCode(), false);
        if (!verify) {
            return ResponseEntity.badRequest().body("短信验证失败");
        }
        return ResponseEntity.ok("短信验证成功");
    }

}
